package com.neuedu.it.mylink.controller;

import com.neuedu.it.mylink.controller.vo.Result;
import com.neuedu.it.mylink.dao.LinkDao;
import com.neuedu.it.mylink.entity.Link;
import com.neuedu.it.mylink.entity.User;
import com.neuedu.it.mylink.service.LinkService;
import com.neuedu.it.mylink.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/links")
public class LinkController {
    // 注入dao
    @Autowired
    private LinkService lkService;
    @Autowired
    private UserService userService;

    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1")int pageIndex,
                       @RequestParam(defaultValue = "") String findname,
                       @RequestParam(defaultValue = "")String findphone,
                       HttpServletRequest req){
        User user = (User) req.getAttribute("user");
       Pageable pageable= PageRequest.of(pageIndex-1,4, Sort.by(Sort.Direction.ASC,"name"));
       Page<Link> page=lkService.page(findname,findphone,user.getId(),pageable);
       return new Result(2000,"success",page);
    }

    @PostMapping("/")
    public Result add(Link link, HttpServletRequest req){
        User user = (User) req.getAttribute("user");
        link.setUserId(user.getId());
        lkService.add(link);
        return new Result(2000,"success",null);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int id,HttpServletRequest req){
        User user = (User) req.getAttribute("user");
        Link lk= lkService.getOne(id);
        if(lk.getUserId()!=user.getId()){
            return new Result(4003,"无权限",null);
        }
        lkService.delete(id);
        return new Result(2000,"success",null);
    }
    @GetMapping("/{id}")
    public Result getOne(@PathVariable("id") int id,HttpServletRequest req){
        User user = (User) req.getAttribute("user");
        Link lk= lkService.getOne(id);
        if(lk.getUserId()!=user.getId()){
            return new Result(4003,"无权限",null);
        }
        return new Result(2000,"success",lk);
    }
    @PutMapping("/")
    public Result update(@RequestBody Link link,HttpServletRequest req){
        User user = (User) req.getAttribute("user");
        Link lk= lkService.getOne(link.getId());
        if(lk.getUserId()!=user.getId()){
            return new Result(4003,"无权限",null);
        }
        lkService.update(link);
        return new Result(2000,"success",lk);
    }




}
